package com.dyh.quickdemozwei.controller;

import com.dyh.quickdemozwei.beanReplace.BeanReplace;
import com.dyh.quickdemozwei.beanReplace.BeanReplaceBiz;
import com.dyh.quickdemozwei.beanReplace.BeanReplaceDemoBiz;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class BeanReplaceController implements ApplicationContextAware {

    @Autowired
    BeanReplaceBiz beanReplaceBiz;


    //((BeanReplaceDemoBiz) ac.getBean("beanReplaceDemoBiz")).hello("dawd",11)


    ApplicationContext ac;
    /*
    [Request processing failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beanReplaceController':
    */
//    @Resource
//    BeanReplaceDemoBiz beanReplaceDemoBiz;

    @RequestMapping("/call")
    public Object call(){

        System.out.println("dawdaw");
        return "ok";
//        return beanReplaceDemoBiz.hello("dadka",1);
    }


    @RequestMapping("/replace")
    public Object replace() throws InstantiationException, IllegalAccessException {
        BeanReplace beanReplace = new BeanReplace();
        beanReplace.setBeanName("beanReplaceDemoBiz");
        beanReplace.setSource(
                "package com.dyh.quickdemozwei.beanReplace;\n" +
                        "\n" +
                        "import org.apache.logging.log4j.LogManager;\n" +
                        "import org.apache.logging.log4j.Logger;\n" +
                        "import org.springframework.stereotype.Service;\n" +
                        "\n" +
                        "@Service\n" +
                        "public class BeanReplaceDemoBiz {\n" +
                        "\n" +
                        "    private Logger logger = LogManager.getLogger(BeanReplaceDemoBiz.class);\n" +
                        "\n" +
                        "    public String hello(String str,Integer i){\n" +
                        "        logger.info(\"入参! str={} i={}\",str,i);\n" +
                        "        return str+i+\"!\";\n" +
                        "    }\n" +
                        "\n" +
                        "}\n"
        );
        beanReplaceBiz.replace(beanReplace);

        return "ok";
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ac = applicationContext;
    }
}
